<template>
  <el-form :model="search" label-width="auto">
    <div>
      <span>订单号</span>
      <el-input
        label="订单号"
        v-model="search.orderNo"
        style="width: 240px"
        placeholder="请输入订单号"
      />

      <span>收货人</span>
      <el-input
        v-model="search.consignee"
        style="width: 240px"
        placeholder="请输入收货人"
      />
      
      <span>手机号</span>
      <el-input
        v-model="search.phone"
        style="width: 240px"
        placeholder="请输入手机号"
      />
    </div>
    <div>
      <span>订单状态</span>
      <el-select
        v-model="search.orderState"
        placeholder="请选择订单状态"
        size="large"
        style="width: 270px; margin: 0 20px 20px 0;"
      >
        <el-option
          v-for="item in orderStateOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>    

      <span>选择时间</span>
      <el-date-picker
        v-model="search.date"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 390px; margin: 0 20px 20px 0;"
      />
      
      <el-button
        type="primary"
        style="margin-bottom: 20px;"
        @click="handleSearch"
      >搜索</el-button>
    </div>
  </el-form>

  <el-table
    :data="tableData"
    style="width: 100%"
    :row-class-name="tableRowClassName"
  >
    <el-table-column prop="orderTime" label="下单时间" />
    <el-table-column prop="orderNo" label="订单号" />
    <el-table-column prop="consignee" label="收货人" />
    <el-table-column prop="phone" label="手机号" />
    <el-table-column prop="orderState" label="订单状态" />
    <el-table-column prop="orderAmount" label="订单金额" 
      :formatter="formatAmount"
    />
    <el-table-column prop="deliverAddress" label="送货地址" />
    <el-table-column prop="deliveryTime" label="送达时间" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button
          type="text"
          @click="handleDetail(scope.row.id)"
        >查看</el-button>
        <el-button
          type="text"
          @click="handleEdit(scope.row)"
        >编辑</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="search.currentPage"
      v-model:page-size="search.pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 编辑组件 -->
  <el-drawer
    v-model="drawerVisible"
    title="编辑订单信息"
    direction="rtl"
    size="40%"
  >
    <div class="demo-drawer__content">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="订单号">
          <el-input v-model="editForm.orderNo" disabled />
        </el-form-item>
        <el-form-item label="下单时间">
          <el-input v-model="editForm.orderTime" disabled />
        </el-form-item>
        <el-form-item label="收货人">
          <el-input v-model="editForm.consignee" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="送货地址">
          <el-input v-model="editForm.deliverAddress" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-input v-model="editForm.orderState" disabled />
        </el-form-item>
        <el-form-item label="订单金额">
          <el-input :value="`￥${editForm.orderAmount.toFixed(2)}`" disabled />
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="loading">保存</el-button>
      </div>
    </div>
  </el-drawer>

  <!-- 查看组件 -->
  <el-dialog v-model="detailDialogVisible" title="订单详情" width="40%">
    <el-form label-width="120px">
      <el-form-item label="订单号">
        <el-input v-model="detailForm.orderNo" disabled />
      </el-form-item>
      <el-form-item label="下单时间">
        <el-input v-model="detailForm.orderTime" disabled />
      </el-form-item>
      <el-form-item label="收货人">
        <el-input v-model="detailForm.consignee" disabled />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="detailForm.phone" disabled />
      </el-form-item>
      <el-form-item label="送货地址">
        <el-input v-model="detailForm.deliverAddress" disabled />
      </el-form-item>
      <el-form-item label="订单状态">
        <el-input v-model="detailForm.orderState" disabled />
      </el-form-item>
      <el-form-item label="订单金额">
        <el-input :value="`￥${detailForm.orderAmount.toFixed(2)}`" disabled />
      </el-form-item>
      <el-form-item label="送达时间">
        <el-input v-model="detailForm.deliveryTime" disabled />
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" v-model="detailForm.remarks" disabled />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getOrderList, getOrderDetail, editOrder } from '../../api/order'
import dayjs from 'dayjs'

// 订单状态选项
const orderStateOptions = ref([
  { value: '已受理', label: '已受理' },
  { value: '派送中', label: '派送中' },
  { value: '已完成', label: '已完成' },
  { value: '已取消', label: '已取消' },
])

// 表格数据（初始加载空数据，页面初始化后加载默认数据）
const tableData = ref<Order[]>([])
const search = reactive<{
  currentPage: number,
  pageSize: number,
  orderNo?: string,
  consignee?: string,
  phone?: string,
  orderState?: string,
  date?: string[]
}>({
  currentPage: 1,
  pageSize: 5,
  orderNo: '',
  consignee: '',
  phone: '',
  orderState: '',
  date: []
})

// 编辑抽屉相关
const drawerVisible = ref(false)
const loading = ref(false)
const editForm = reactive<Order>({
  id: 0,
  orderNo: '',
  orderTime: '',
  phone: '',
  consignee: '',
  deliverAddress: '',
  deliveryTime: '',
  remarks: '',
  orderAmount: 0,
  orderState: ''
})

// 详情对话框相关
const detailDialogVisible = ref(false)
const detailForm = reactive<Order>({
  id: 0,
  orderNo: '',
  orderTime: '',
  phone: '',
  consignee: '',
  deliverAddress: '',
  deliveryTime: '',
  remarks: '',
  orderAmount: 0,
  orderState: ''
})

// 接口数据映射类型
interface Order {
  id: number,
  orderNo: string,
  orderTime: string,
  phone: string,
  consignee: string,
  deliverAddress: string,
  deliveryTime: string,
  remarks: string,
  orderAmount: number,
  orderState: string
}

// 行样式类
const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  if (rowIndex === 1) return 'warning-row'
  if (rowIndex === 3) return 'success-row'
  return ''
}

// 金额格式化
const formatAmount = (row: Order, column: any) => {
  return `￥${row.orderAmount.toFixed(2)}`
}

// 总记录数
const total = ref(0)

// 页面初始化加载数据
const loadInitialData = async () => {
  try {
    const defaultParams = {
      currentPage: 1, // 默认第一页
      pageSize: 5, // 默认每页5条
      // 其他参数为空，获取全部数据
    };
    const response = await getOrderList(defaultParams);
    if (response.data) {
      tableData.value = response.data.map(item => ({
        ...item,
        orderTime: dayjs(item.orderTime).format('YYYY-MM-DD HH:mm:ss'),
        deliveryTime: dayjs(item.deliveryTime).format('YYYY-MM-DD HH:mm:ss')
      }));
      total.value = response.total;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (err) {
    console.error('初始化数据加载失败:', err);
    ElMessage.error('数据加载失败，请重试');
  }
}

// 搜索方法
const handleSearch = async () => {
  try {
    const params = {
      ...search,
      currentPage: search.currentPage,
      pageSize: search.pageSize,
      startTime: search.date.length === 2 
        ? dayjs(search.date[0]).format('YYYY-MM-DD HH:mm:ss') 
        : undefined,
      endTime: search.date.length === 2 
        ? dayjs(search.date[1]).format('YYYY-MM-DD HH:mm:ss') 
        : undefined,
    };

    const response = await getOrderList(params);
    if (response.data) {
      tableData.value = response.data.map(item => ({
        ...item,
        orderTime: dayjs(item.orderTime).format('YYYY-MM-DD HH:mm:ss'),
        deliveryTime: dayjs(item.deliveryTime).format('YYYY-MM-DD HH:mm:ss')
      }));
      total.value = response.total;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (err) {
    console.error('搜索失败:', err);
    ElMessage.error('搜索失败，请重试');
  }
}

// 页面加载时初始化数据
onMounted(() => {
  loadInitialData(); // 初始化加载默认数据
});

// 查看详情方法
const handleDetail = async (id: number) => {
  try {
    const res = await getOrderDetail(id)
    Object.assign(detailForm, {
      ...res.data,
      orderTime: dayjs(res.data.orderTime).format('YYYY-MM-DD HH:mm:ss'),
      deliveryTime: dayjs(res.data.deliveryTime).format('YYYY-MM-DD HH:mm:ss')
    })
    detailDialogVisible.value = true
  } catch (err) {
    console.error('获取订单详情失败:', err)
    ElMessage.error('获取订单详情失败')
  }
}

// 打开编辑抽屉
const handleEdit = async (row: Order) => {
  try {
    const res = await getOrderDetail(row.id)
    Object.assign(editForm, {
      ...res.data,
      orderTime: dayjs(res.data.orderTime).format('YYYY-MM-DD HH:mm:ss'),
      deliveryTime: dayjs(res.data.deliveryTime).format('YYYY-MM-DD HH:mm:ss')
    })
    drawerVisible.value = true
  } catch (err) {
    console.error('获取订单详情失败:', err)
    ElMessage.error('获取订单详情失败')
  }
}

// 保存编辑
const handleSave = async () => {
  try {
    loading.value = true
    const submitData = {
      id: editForm.id,
     consignee: editForm.consignee,
     phone: editForm.phone,
     deliverAddress: editForm.deliverAddress,
     orderNo: editForm.orderNo,
     orderTime: editForm.orderTime,
     deliveryTime: editForm.deliveryTime,
     remarks: editForm.remarks,
     orderAmount: editForm.orderAmount,
     orderState: editForm.orderState
    };

    await editOrder(submitData);
    ElMessage.success('修改成功')

    // 更新本地数据
    loadInitialData(); 
    drawerVisible.value = false
  } catch (err) {
    console.error('保存失败:', err)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 分页切换时触发搜索
const handleCurrentChange = (val: number) => {
  search.currentPage = val;
  handleSearch(); // 切换分页时调用搜索
}

const handleSizeChange = (val: number) => {
  search.pageSize = val;
  handleSearch(); // 切换每页数量时调用搜索
}
</script>

<style scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.el-input {
  margin: 0 20px 20px 0;
}
.demo-pagination-block {
  margin-top: 20px;
}
</style>